<template>
  <ToolboxWindow
    title="Snapshot loader"
    :show="show"
    :width="400"
    @close="close"
    v-loading="isLoading"
  >
    <el-form size="small" label-width="72px">
      <el-form-item label="Start time">
        <el-date-picker
          v-model="formData.from.date"
          style="width: 120px"
          type="date"
          placeholder="Pick a day"
          :clearable="false"
          @change="setRange()"
        />
        <span style="padding: 0 8px">-</span>
        <el-time-select
          v-model="formData.from.time"
          style="width: 90px"
          start="00:00"
          step="00:15"
          end="23:45"
          placeholder="Select time"
          :clearable="false"
          @change="setRange()"
        />
      </el-form-item>
      <el-form-item label="End time">
        <el-date-picker
          v-model="formData.to.date"
          style="width: 120px"
          type="date"
          placeholder="Pick a day"
          :clearable="false"
          @change="setRange()"
        />
        <span style="padding: 0 8px">-</span>
        <el-time-select
          v-model="formData.to.time"
          style="width: 90px"
          start="00:00"
          step="00:15"
          end="23:45"
          placeholder="Select time"
          :clearable="false"
          @change="setRange()"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="small" @click="handleLoad">
          <el-icon><Download /></el-icon>
          <span>Load</span>
        </el-button>
        <span style="padding: 0 16px"></span>
        <el-button
          :disabled="flowStore.loaderType != 'snapshot'"
          type="primary"
          size="small"
          link
          @click="handleClear"
        >
          <el-icon><Delete /></el-icon>
          <span>Clear</span>
        </el-button>
      </el-form-item>
    </el-form>
    <div v-if="result && !isLoading">
      <!-- controller -->
      <el-divider />
      <div>
        <el-slider
          v-model="flowStore.loaderConfig.snapshot.pointer"
          :min="0"
          :max="content.length - 1"
          :step="1"
          :show-stops="content.length < 40"
          :format-tooltip="selectedTooltip"
          @change="handleSelect"
        />
      </div>
      <div class="bar" style="padding-top: 16px">
        <el-button link type="primary" size="small" @click="handleJump(-4)"
          >-60</el-button
        >
        <el-button link type="primary" size="small" @click="handleJump(-2)"
          >-30</el-button
        >
        <el-button link type="primary" size="small" @click="handleJump(-1)"
          >-15</el-button
        >
        <span style="padding: 0 48px"> </span>
        <el-button link type="primary" size="small" @click="handleJump(1)"
          >+15</el-button
        >
        <el-button link type="primary" size="small" @click="handleJump(2)"
          >+30</el-button
        >
        <el-button link type="primary" size="small" @click="handleJump(4)"
          >+60</el-button
        >
      </div>
      <div class="bar" style="padding-top: 24px">
        <el-text type="success" size="small">
          <el-icon><SuccessFilled /></el-icon>
          <span style="padding-left: 4px">Loaded</span>
        </el-text>
        <el-divider direction="vertical" />
        <el-text type="info" size="small">Total:</el-text>
        <el-text>{{ content.length }}</el-text>
        <el-divider direction="vertical" />
        <el-text type="info" size="small">Selected:</el-text>
        <el-text>{{ selectedSnapTimeShort }}</el-text>
      </div>
    </div>
  </ToolboxWindow>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import ToolboxWindow from "@/components/ToolboxWindow";
import useFlowStore from "@/store/flow.js";
import dayjs from "dayjs";
import axios from "axios";

const flowStore = useFlowStore();
const config = flowStore.loaderConfig.snapshot;

const show = computed(
  () =>
    flowStore.loaderType == "snapshot" ||
    flowStore.chartConfig.gnenralChart.showSnapshot
);

const close = () => {
  flowStore.chartConfig.gnenralChart.showSnapshot = false;
};

const formData = ref({
  from: {
    date: null,
    time: null,
  },
  to: {
    date: null,
    time: null,
  },
});

const setRange = () => {
  let from =
    dayjs(formData.value.from.date).format("YYYY-MM-DD") +
    " " +
    formData.value.from.time +
    ":00";
  let to =
    dayjs(formData.value.to.date).format("YYYY-MM-DD") +
    " " +
    formData.value.to.time +
    ":00";
  flowStore.loaderConfig.snapshot.from = dayjs(from).toDate();
  flowStore.loaderConfig.snapshot.to = dayjs(to).toDate();
  params.value = {
    from,
    to,
  };
  console.log("SnapshotLoader", from, to);
};

const params = ref(null);
const result = ref(null);

const content = computed(() => flowStore.loaderConfig.snapshot.content);
// const content = flowStore.loaderConfig.snapshot.content;

const selectedCentent = computed(
  () => content.value[flowStore.loaderConfig.snapshot.pointer]
);
const selectedBegTime = computed(() => selectedCentent.value.begTime);
const selectedSnapTime = computed(() => selectedCentent.value.snapTime);
const selectedSnapTimeShort = computed(() =>
  selectedCentent.value.snapTime.slice(5, 16)
);
const selectedTooltip = (val) => selectedSnapTimeShort.value;

const handleSelect = () => {
  flowStore.begTime = selectedBegTime.value;
  flowStore.version = new Date().getTime();
  flowStore.rawData = selectedCentent.value.snapData.map(
    (cell) => cell.content
  );
};

const handleJump = (step) => {
  if (
    flowStore.loaderConfig.snapshot.pointer + step >
    flowStore.loaderConfig.snapshot.content.length - 1
  ) {
    flowStore.loaderConfig.snapshot.pointer =
      flowStore.loaderConfig.snapshot.content.length - 1;
  } else if (flowStore.loaderConfig.snapshot.pointer + step < 0) {
    flowStore.loaderConfig.snapshot.pointer = 0;
  } else {
    flowStore.loaderConfig.snapshot.pointer =
      flowStore.loaderConfig.snapshot.pointer + step;
  }
  handleSelect();
};

const setDefaultRange = () => {
  if (
    flowStore.loaderConfig.snapshot.from == null ||
    flowStore.loaderConfig.snapshot.to == null
  ) {
    let from = dayjs().subtract(1, "day").minute(0).second(0).toDate();
    let to = dayjs().minute(0).second(0).toDate();
    flowStore.loaderConfig.snapshot.from = from;
    flowStore.loaderConfig.snapshot.to = to;
  }
  formData.value.from.date = flowStore.loaderConfig.snapshot.from;
  formData.value.to.date = flowStore.loaderConfig.snapshot.to;
  formData.value.from.time = dayjs(flowStore.loaderConfig.snapshot.from).format(
    "HH:mm"
  );
  formData.value.to.time = dayjs(flowStore.loaderConfig.snapshot.to).format(
    "HH:mm"
  );
  setRange();
};

const isLoading = ref(false);
const handleLoad = () => {
  isLoading.value = true;
  axios
    .post("api/flow_ntfm_get_snapshot.php", params.value)
    .then((response) => {
      if (response.data && response.data.success) {
        flowStore.loaderConfig.snapshot.content = response.data.content;
        flowStore.loaderConfig.snapshot.pointer = 0;
        flowStore.begTime = response.data.content[0].begTime;
        flowStore.rawData = response.data.content[0].snapData.map(
          (cell) => cell.content
        );
        flowStore.loaderType = "snapshot";
        flowStore.tags = response.data.tags;
        flowStore.freshness = 0;
        flowStore.autoRefresh = false;
        flowStore.version = new Date().getTime();
        result.value = response.data;
        isLoading.value = false;
        console.log("handleLoad", response.data);
      }
    })
    .catch((error) => {
      isLoading.value = false;
      console.error("SnapshotLoader", "handleLoad", error);
    });
};

const handleClear = () => {
  flowStore.loaderConfig.snapshot.content = [];
  flowStore.loaderConfig.snapshot.pointer = 0;
  flowStore.loaderType = "real";
  flowStore.autoRefresh = true;
  result.value = null;
  isLoading.value = true;
  flowStore
    .getFlowData()
    .then(() => (isLoading.value = false))
    .catch(() => (isLoading.value = false));
};

onMounted(() => {
  setDefaultRange();
});
</script>

<style scoped>
.bar {
  display: flex;
  align-items: center;
  justify-content: space-around;
  /* padding-top: 16px; */
}
</style>
